package com.itheima.reggie.controller;

import com.alipay.api.AlipayApiException;
import com.itheima.reggie.common.AliPayServer;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.Pay;
import com.itheima.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;


@Controller
@Slf4j
public class PayController {

    @Autowired
    private AliPayServer aliPayServer;

    @Autowired
    private OrderService orderService;

    @RequestMapping("/notify")
    @ResponseBody
    public void notifyPay(@RequestParam Map<String,String> map,HttpServletResponse response) throws AlipayApiException, IOException {
        boolean s = aliPayServer.notifyPay(map);
        if (s){
            response.sendRedirect("http://localhost/front/page/pay-success.html");
        }
    }

    @RequestMapping("/pay/{orderId}")
    @ResponseBody
    public void pay(HttpServletRequest httpRequest,
                       HttpServletResponse httpResponse,@PathVariable Long orderId) throws ServletException, IOException {
        Orders order = orderService.getById(orderId);
        Pay pay=new Pay();
        pay.setOrderId(order.getId().toString());
        pay.setPrice(order.getAmount().toString());
        pay.setProductId(order.getNumber());
        String form = aliPayServer.pay("http://localhost/notify", pay);
        httpResponse.setContentType("text/html;charset=" + "utf-8");
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }
}
